﻿using System;
using System.ComponentModel;
using System.ServiceModel;
using System.ServiceProcess;
using System.Configuration;
using System.Configuration.Install;
using System.Diagnostics;

using SsrsRenderStudio.Shared;
using SsrsRenderStudio.Configuration;
using SsrsRenderStudio.Wcf;
using SsrsRenderStudio.Wcf.Host;
using SsrsRenderStudio.Wcf.ServiceImpl;
using SsrsRenderStudio.Wcf.Services;

namespace SsrsRenderStudio.WindowsService
{
    public class RenderStudioServer: ServiceBase
    {
        private static RenderStudioServer _service = null;

        public static void Main(string[] args)
        {
            _service = new RenderStudioServer();
            //ServiceBase.Run(service);

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            if (Environment.UserInteractive)
            {
                _service.OnStart(args);
                Console.WriteLine("[press enter to stop service]");
                Console.ReadLine();
                _service.OnStop();
                Console.WriteLine("[press enter again to exit app]");
                Console.ReadLine();
            }
            else
            {
                ServiceBase.Run(_service);
            }
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                Logger.Log("00002", ((Exception)e.ExceptionObject).Message);
            }
            catch { }
            finally
            {
                if (bool.Parse(Properties.Resources.WINDOWS_SERVICE_SHUTDOWN_ON_UNHANDLED_EXCEPTION))
                {
                    _service.Stop();
                }
            }
        }

        private ServiceController SsrsRenderStudioServer_SC;
        private CustomServiceHost _svcUser = null;
        //private CustomServiceHost _svcAdmin = null;

        public RenderStudioServer()
        {
            this.ServiceName = ConfigurationManager.RENDER_STUDIO_SERVICE_NAME;
        }

        protected override void OnStart(string[] args)
        {
            Logger.Log("60005");

            try
            {
                if (_svcUser != null)  _svcUser.Close();
                _svcUser = new CustomServiceHost(typeof(RenderStudioUserService));
                if (_svcUser.IsValidInstance)
                {
                    _svcUser.Open();
                    WcfConfiguration.PrintServiceInfo(_svcUser);
                }
                else
                {
                    throw new Exception("Service failed to configure its endpoints: " + _svcUser.LastException);
                }

                /*
                if (_svcAdmin != null) _svcAdmin.Close();
                _serviceHostSystem = new CustomServiceHost(typeof(RenderStudioSystemService));
                if (_serviceHostSystem.ServiceConfiguredSuccessfully)
                {
                    _serviceHostSystem.Open();
                    WcfConfiguration.PrintServiceInfo(_serviceHostSystem);
                }
                else
                {
                    throw new Exception("Service failed to configure its endpoints." + _serviceHostSystem.LastException);
                }
                */ 
            }
            catch (Exception ex)
            {
                Logger.Log("00000", ex.Message);
            }

            base.OnStart(args);
            Logger.Log("60006");
        }

        protected override void OnStop()
        {
            Logger.Log("60007");

            DeviceContextCache.PurgeCache();
            ReportCache.PurgeCache();

            if (_svcUser != null)
            {
                try
                {
                    _svcUser.Close();
                }
                catch (Exception ex)
                {
                    Logger.Log("00001", ex.Message);
                }
                _svcUser = null;
            }

            /*
            if (_serviceHostSystem != null)
            {
                try
                {
                    _serviceHostSystem.Close();
                }
                catch (Exception ex)
                {
                    Logger.Log("SERVICE STOP ERROR: " + ex.Message);
                }
                _serviceHostSystem = null;
            }
            */

            base.OnStop();
            Logger.Log("60008");
            Logger.DestroyLogger();
        }

        private void InitializeComponent()
        {
            this.SsrsRenderStudioServer_SC = new System.ServiceProcess.ServiceController();
            this.SsrsRenderStudioServer_SC.ServiceName = "SsrsRenderStudioServer";
            this.ServiceName = "SsrsRenderStudioServer";
        }
    }

    /* DEPRACATED: Installer was built with designer!
    // Provide the ProjectInstaller class which allows 
    // the service to be installed by the Installutil.exe tool
    [RunInstaller(true)]
    public class ProjectInstaller : Installer
    {
        private ServiceProcessInstaller process;
        private ServiceInstaller service;

        public ProjectInstaller()
        {
            process = new ServiceProcessInstaller();
            process.Account = ServiceAccount.LocalSystem;
            service = new ServiceInstaller();
            service.ServiceName = ConfigurationManager.RENDER_STUDIO_SERVICE_NAME ;
            Installers.Add(process);
            Installers.Add(service);
        }
    }
    */
}
